<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="120px" size="mini">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="周次" prop="weekDate">
            <el-date-picker
              v-model="formItem.weekDate"
              type="week"
              format="yyyy 第 WW 周"
              placeholder="选择周次"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="onWeekChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="companyCode">
            <el-select v-model="formItem.companyCode" filterable clearable placeholder="请选择单位" :disabled="unableSelectUnit" @change="onChange">
              <el-option v-for="item in availableInstitutions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报告人" prop="userCode">
            <el-select v-model="formItem.userCode" placeholder="请选择报告人" filterable clearable :disabled="unableSelectUnit" @change="onChangeUserCode">
              <el-option v-for="item in availableUsers" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务项目" prop="serviceItem">
            <el-input v-model="formItem.serviceItem" placeholder="请输入服务项目" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实际到场人数" prop="actualAttendanceNumber">
            <el-input-number v-model="formItem.actualAttendanceNumber" :min="0" :max="999999" :precision="0" label="实际到场人数" style="width:100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="本周工作完成情况" prop="weekWorkInfo">
            <el-input v-model="formItem.weekWorkInfo" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="总结描述" prop="summaryDesc">
            <el-input v-model="formItem.summaryDesc" placeholder="请输入总结描述" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="下周工作计划" prop="nextWeekWorkPlan">
            <el-input v-model="formItem.nextWeekWorkPlan" placeholder="请输入下周工作计划" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="问题记录及解决方案" prop="problemOrSolution">
            <el-input v-model="formItem.problemOrSolution" placeholder="请输入问题记录及解决方案" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formItem.remark" placeholder="请输入备注" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件">
            <el-upload
              class="upload-demo"
              :headers="headers"
              :action="importUrl"
              :file-list="formItem.attachment"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-remove="handleRemove"
              :show-file-list="true"
            >
              <el-button size="small" type="primary" icon="el-icon-upload2">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getInfoByCode as projectInfo } from '@neu/dcom-ui/api/project'
import { create, update, detail } from '@neu/dcom-ui/api/operationSupportWeekly'
import { weekBegin, weekEnd } from '@neu/biz-core/utils/utils'
import { page as dayList } from '@neu/dcom-ui/api/workDaily'
import { deepClone } from '@neu/biz-core/utils'
import { formatDate, getFirstDayOfWeekOfYear } from '@neu/biz-core/utils/utils'
import { mapState, mapGetters } from 'vuex'
import { uploadFileUrl } from '@neu/dcom-ui/api/workDaily'
import { getToken } from '@neu/biz-core/utils/auth'
// 定义一个表单原始项
const formItem = {
  /** 单位名称 */
  companyName: '',
  /** 单位编码 */
  companyCode: '',
  /** 创建人员 */
  userName: '',
  /** 创建人员编码 */
  userCode: '',
  /** 服务项目 */
  serviceItem: '',
  /** 实际到场人数 */
  actualAttendanceNumber: 1,
  /** 本周工作情况 */
  weekWorkInfo: '',
  /** 下周工作计划 */
  nextWeekWorkPlan: '',
  /** 总结描述 */
  summaryDesc: '',
  /** 问题记录及解决方案 */
  problemOrSolution: '',
  /** 备注 */
  remark: '',
  /** 周次 */
  weekDate: formatDate(getFirstDayOfWeekOfYear(new Date())),
  /** 附件 */
  attachment: []
}
let project = {}
const formRules = {
  serviceItem: [{ required: true, message: '服务项目不能为空', trigger: 'blur' }],
  companyCode: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
  userCode: [{ required: true, message: '报告人不能为空', trigger: 'blur' }],
  weekDate: [{ required: true, message: '周次不能为空', trigger: 'blur' }]
}

export default {
  name: 'OperationSupportWeeklyEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    const data = {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      /** 行数 */
      rows: 2,
      // 所有单位
      // availableInstitutions: [],
      // 表单验证规则
      rules: { ...formRules },
      availableUsers: [],
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      importUrl: uploadFileUrl
    }
    return data
  },
  computed: {
    ...mapState({
      name: state => state.user.name
    }),
    ...mapGetters([
      'roles'
    ]),
    defaultUserCode: function() {
      const projectUserInfo = this.$store.getters['dcom/projectUserInfo']
      const defaultInstitute = projectUserInfo.institutions ? projectUserInfo.institutions.find(it => it.code === it.defaultInstituteCode) : null
      if (defaultInstitute) {
        return defaultInstitute.residentUserCode
      }
      return ''
    },
    availableInstitutions: function() {
      return this.$store.getters['dcom/projectUserInfo'].institutions
    },
    // 是否可选择厅局
    unableSelectUnit() {
      return this.roles.some(r => r === 'worker')
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    // this.availableInstitutions = this.$store.getters['dcom/projectUserInfo'].institutions
    // this.formItem.companyCode = this.$store.getters['dcom/projectUserInfo'].defaultInstituteCode
    // const inst = this.availableInstitutions.find(it => it.code === this.formItem.companyCode)
    // if (inst) {
    //   let currentResidentUser = inst.residents.find(it => it.name === this.name)
    //   if (!currentResidentUser) {
    //     currentResidentUser = inst.residents.length > 0 ? inst.residents[0] : {}
    //   }

    //   this.formItem.userCode = currentResidentUser.username
    //   this.availableUsers = [...inst.residents, ...inst.users]
    // }
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          const data = response.data
          if (data.attachment) {
            const fileJoins = data.attachment.split('||')
            data.attachment = fileJoins.map(it => {
              const fsInfo = it.split('@@')
              return {
                fsId: fsInfo[0],
                name: fsInfo[1]
              }
            })
          } else {
            data.attachment = []
          }
          this.formItem = {
            ...data
          }
          this.initDefaultIncidentUser()
          // if (this.formItem.companyCode) {
          //   this.getDayWorkList(this.formItem.companyCode)
          // }
        })
      } else {
        this.formItem = {
          ...formItem
        }
        this.formItem.companyCode = this.$store.getters['dcom/projectUserInfo'].defaultInstituteCode
        this.initDefaultIncidentUser()
        this.getProject()
        if (this.$store.getters['dcom/projectUserInfo'].defaultInstituteCode) {
          this.getDayWorkList(this.$store.getters['dcom/projectUserInfo'].defaultInstituteCode)
        }
      }
    },
    initDefaultIncidentUser() {
      const inst = this.availableInstitutions.find(it => it.code === this.formItem.companyCode)
      if (inst) {
        let currentResidentUser = inst.residents.find(it => it.name === this.name)
        if (!currentResidentUser) {
          currentResidentUser = inst.residents.length > 0 ? inst.residents[0] : {}
        }
        this.formItem.userCode = currentResidentUser.username
        this.formItem.userName = currentResidentUser.name
        this.availableUsers = [...inst.residents, ...inst.users]
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            // 公司名称
            const institutions = this.availableInstitutions.find(e => this.formItem.companyCode === e.code)
            this.formItem.companyName = institutions ? institutions.name : ''
            // 人员名称
            // const user = this.getUsers(this.formItem.companyCode).find(e => this.formItem.userCode === e.username)
            // this.formItem.userName = user ? user.name : ''
            const deepCloneForm = deepClone(this.formItem)
            // 将附件转为字符串存储
            if (deepCloneForm.attachment.length > 0) {
              deepCloneForm.attachment = deepCloneForm.attachment.map(it => it.fsId + '@@' + it.name).join('||')
            } else {
              deepCloneForm.attachment = ''
            }
            if (updated) {
              resolve(update(this.id, deepCloneForm))
            } else {
              resolve(create(deepCloneForm))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    },
    onChange(value) {
      this.formItem.userCode = ''
      const inst = this.availableInstitutions.find(it => it.code === value)
      if (inst) {
        let currentResidentUser = inst.residents.find(it => it.name === this.name)
        if (!currentResidentUser) {
          currentResidentUser = inst.residents.length > 0 ? inst.residents[0] : {}
        }

        this.formItem.userCode = currentResidentUser.username
        this.formItem.userName = currentResidentUser.name
        this.availableUsers = [...inst.residents, ...inst.users]
      }
      // 清空周任务
      this.formItem.weekWorkInfo = ''
      if (value) {
        this.getDayWorkList(value)
      }
    },
    getUsers(value) {
      let user = []
      const data = deepClone(this.availableInstitutions) || []
      const one = data.find(e => e.code === value)
      user = (one || {})['users'] || []
      if (one) {
        user.push({ name: one.residentUserName, username: one.residentUserCode })
      }
      return user
    },
    getProject() {
      projectInfo('HN').then(res => {
        project = res.data
        this.formItem.serviceItem = project.name
      })
    },
    getDayWorkList(unitCode) {
      let dateTime = new Date()
      if (this.formItem.weekDate) {
        dateTime = new Date(this.formItem.weekDate)
      } else {
        dateTime = new Date(this.formItem.createTime)
      }
      this.formItem.weekWorkInfo = ''
      dayList({
        s_unitCode: unitCode,
        s_afEqReportDate: weekBegin(dateTime.getTime()),
        s_beEqReportDate: weekEnd(dateTime.getTime()),
        sort: ['dailyReportDate,asc', 'serviceStartTime,asc'],
        size: 2000
      }).then(res => {
        res.data.forEach(item => {
          this.formItem.weekWorkInfo += '日期：' + formatDate(item.dailyReportDate, 'YYYY-MM-DD') + ' ' + formatDate(item.serviceStartTime, 'HH:mm') + '至' + formatDate(item.serviceEndTime, 'HH:mm') + '  工作内容：' + item.jobContent + '\n'
        })
      })
    },
    onWeekChange(val) {
      this.getDayWorkList(this.formItem.companyCode)
    },
    onChangeUserCode(incidentUserCode) {
      const user = this.availableUsers.find(item => item.username === incidentUserCode)
      this.formItem.userName = user.name
    },
    /** 文件上传成功 */
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.attachment.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachment.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    /** 文件上传失败 */
    handleError(err, file, fileList) {
      console.log(err)
    },
    /** 文件移除 */
    handleRemove(file, fileList) {
      this.formItem.attachment.splice(this.formItem.attachment.indexOf(file), 1)
    }
  }
}
</script>
